package com.jhf.youke.base.domain.model.Do;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Strings;
import com.jhf.youke.base.domain.exception.UserException;
import com.jhf.youke.base.domain.model.dto.RegisterCustomerDto;
import com.jhf.youke.base.domain.model.dto.RegisterRegimentalCommanderDto;
import com.jhf.youke.base.domain.model.dto.VideoLoginDto;
import com.jhf.youke.base.domain.model.po.UserPo;
import com.jhf.youke.core.ddd.BaseDoEntity;
import com.jhf.youke.core.entity.Message;
import lombok.Data;

import java.util.*;


/**
 * @author RHJ
 */
@Data
public class UserDo extends BaseDoEntity {

    private static final long serialVersionUID = 282412119286586123L;

    private List<UserRoleDo> userRoles;

    private Set<String> permissionsMap;

    /**用户名 **/
    private String loginName;

    /**密码 **/
    private String password;

    /**二级密码 **/
    private String passwordTwo;

    /**盐值 **/
    private String salt;

    /**姓名 **/
    private String name;

    /**头像 **/
    private String headImage;

    /**性别 0未知 1男 2女 **/
    private Integer sex;

    /**手机号 **/
    private String phone;

    /**地区ID 关联区域表 **/
    private Long areaId;

    /**公众号OpenID **/
    private String openId;

    /**单位ID **/
    private Long companyId;

    /**单位ID **/
    private Long rootId;

    /**详细地址 **/
    private String address;

    /**生日 **/
    private Date birthday;

    /**状态  0：禁用   1：正常 **/
    private Integer status;

    /**部门ID **/
    private Long deptId;

    /**用户类型 1管理员 2B端用户 3供应链 4厂商 5 C端 **/
    private Integer type;

    /**
     * 身份 1 客户 2 团长
     */
    private Integer position;

    private String oldPassword;
    private String newPassword1;
    private String newPassword2;

    private Date startTime;
    private Date endTime;

    private String companyName;

    private String companyIds;

    public UserDo(){

    }
    /** 推荐创建为团长 **/
    public UserDo(UserPo userPo, RegisterRegimentalCommanderDto dto) {
        this.rootId = userPo.getRootId();
        this.companyId = userPo.getCompanyId();
        this.companyName = userPo.getCompanyName();
        this.loginName = dto.getLoginName();
        this.name =dto.getName();
        this.phone = dto.getPhone();
        this.openId = dto.getOpenId();
        this.status = 0;
        this.type= 5;
        this.position = 2;
    }

    /**推荐创建为客户 **/
    public UserDo(UserPo userPo, RegisterCustomerDto dto) {
        this.rootId = userPo.getRootId();
        this.companyId = userPo.getCompanyId();
        this.companyName = userPo.getCompanyName();
        this.loginName = dto.getLoginName();
        this.name =dto.getName();
        this.phone = dto.getPhone();
        this.sex = dto.getSex();
        this.areaId = dto.getAreaId();
        this.openId = dto.getOpenId();
        this.status = 1;
        this.type= 5;
        this.position = 1;
    }

    /** 视频用户注册 **/
    public UserDo(VideoLoginDto dto) {
        this.rootId = dto.getRootId();
        this.companyId = dto.getCompanyId();
        this.companyName = dto.getCompanyName();
        this.loginName = dto.getOpenid();
        this.name = dto.getNickname();
        this.openId = dto.getOpenid();
        this.status = 1;
        this.type = 6;
    }

    private String validateName(String name) {
        if (Strings.isNullOrEmpty(name)) {
            throw new UserException("Name should not be null or empty");
        }
        return name;
    }

    public <T> T requireNonNull(T obj, Object column, String errorMessage) {
        if (Objects.isNull(column)) {
            throw new UserException(errorMessage);
        }
        return obj;
    }

    private UserDo validate(UserDo userDo){
        userDo.requireNonNull(userDo, userDo.getLoginName(),"登录名不能为空")
                .requireNonNull(userDo, userDo.getStatus(),"状态不能为空")
                .requireNonNull(userDo,userDo.getAreaId(), "地区不能为空")
                .requireNonNull(userDo,userDo.getSex(), "姓别不能为空")
                .requireNonNull(userDo,userDo.getCompanyId(),"所属单位不能为空");

        return userDo;
    }

    private UserDo disable(){
        this.status =0;
        return this;
    }

    private UserDo enable(){
        this.status =1;
        return this;
    }

    private UserDo addRoles(List<UserRoleDo> roleList){
        this.userRoles.addAll(roleList);
        return this;
    }

    /** 初始化密码、盐值、MD5 **/
    public UserDo initPassword(){
        this.salt = UUID.randomUUID().toString();
        this.password = DigestUtil.md5Hex(this.password + this.salt);
        return this;
    }

    /** 更新密码 **/
    public UserDo updatePassword(String password){
        this.salt = UUID.randomUUID().toString();
        this.password = DigestUtil.md5Hex(password + this.salt);
        return this;
    }

    /** 检查明文密码是否正确 **/
    public UserDo checkPassword(String password){
        this.requireNonNull(this, password,"原密码不能为空");
        password = DigestUtil.md5Hex(password + this.salt);
        if(this.password.equals(password)){
            return this;
        }else{
            throw new UserException("密码错误！");
        }
    }

    /** 更新密码时检查两次输入密码是否一致 **/
    public UserDo checkTwoPassword(String password1, String password2){
        this.requireNonNull(this, password1,"新密码不能为空");
        if(password1.equals(password2)){
            return this;
        }else{
            throw new UserException("两次密码输入不一致！");
        }
    }

    public void checkStatus(){
        if(this.getStatus() == 0) {
            throw new UserException("用户已停用，请联系管理员");
        }
    }

    public String sagaMsgForCreateRegimentalCommander(Long referrerId){
        Message message = new Message();
        message.setTopic("createSagaConsume");
        message.setGroupName("baseGroup");
        message.setTag("all");
        Map<String, Object> map = new HashMap<>(16);
        map.put("key"+UUID.randomUUID(), "regimental_commander_create_"+this.id);
        map.put("code", "createRegimentalCommander");
        map.put("bizId", this.id);
        map.put("objectId",1);
        Map<String, Object> msg = new HashMap<>(16);
        msg.put("companyId", this.companyId);
        msg.put("userId", this.id);
        msg.put("userName", this.name);
        msg.put("openId", this.openId);
        msg.put("nickName", this.name);
        msg.put("referrer", referrerId);
        map.put("message",msg);
        message.setMessages(map);
        return JSONUtil.toJsonStr(message);
    }

    public String sagaMsgForCreateCustomer(Long saleManId){
        Message message = new Message();
        message.setTopic("createSagaConsume");
        message.setGroupName("baseGroup");
        message.setTag("all");
        Map<String, Object> map = new HashMap<>(16);
        map.put("key"+UUID.randomUUID(), "customer_create_"+this.id);
        map.put("code", "createCustomer");
        map.put("bizId", this.id);
        map.put("objectId",1);
        Map<String, Object> msg = new HashMap<>(16);
        msg.put("name", this.getName());
        msg.put("phone", this.getPhone());
        msg.put("companyId", this.getCompanyId());
        msg.put("sex", this.sex);
        msg.put("areaId", this.areaId);
        msg.put("userId", this.id);
        msg.put("openId", this.openId);
        msg.put("nickName", this.name);
        msg.put("saleMan", saleManId);
        map.put("message",msg);
        message.setMessages(map);
        return JSONUtil.toJsonStr(message);
    }

}


